package com.lzj.dao;

import java.sql.*;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2021/12/2
 */
public class BaseDao {
    protected Connection conn =null;
    protected PreparedStatement pstmt = null;
    protected ResultSet rs = null;
    protected int result = 0;
    public boolean getConn(){//连接数据库
        boolean flag=false;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//配置加载驱动
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/dailyfresh?serverTimezone=Asia/Shanghai&useSSL=false","root","root");
            flag=true;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public ResultSet executeQuery(String sql,Object[] params){//查询
        if(getConn()){
            try {
                pstmt=conn.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1,params[i]);
                }
                rs=pstmt.executeQuery();//执行select语句，返回一个结果集
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return rs;
    }

    public int executeUpdate(String sql,Object[] params){//更新、修改
        if(getConn()){
            try {
                pstmt=conn.prepareStatement(sql);
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1,params[i]);
                }
                result= pstmt.executeUpdate();//返回受影响的行数
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return result;
    }

    public void closeResouce(Connection conn,ResultSet rs,PreparedStatement pstmt){
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
